const fs = require("fs");
const path = require("path");
const url = require("url");

//私有方法
let getFileMime = function(extname){
    let data = fs.readFileSync("./data/mime.json");    //同步读取
    let mimeObj = JSON.parse(data.toString());
    return mimeObj[extname];
}


exports.static = function(req,res,staticPath){
    //1、获取网址
    let pathName = url.parse(req.url).pathname;
    pathName = pathName == "/" ? "/index.html" : pathName;
    let extname = path.extname(pathName);
    //2、通过fs模块读取文件 
    if(pathName != "/favicon.ico"){
 
        try {
            let data = fs.readFileSync("./" + staticPath + pathName);
            if(data){
                let mime = getFileMime(extname);
                res.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'}); 
                res.end(data)
            }
        } catch (error) {
            console.log("======error======");
        }
    }
}



